<?php

namespace App\Http\Controllers\Backend;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\ProductCategory;
use App\Transformers\ProductCategoryTransformer;
use Illuminate\Support\Facades\DB;


class ProductCategoryController extends Controller
{

    /**
     * 统计商品分类天
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function staticCategoryDay(Request $request) {
        $bistro = $request->user('bistro');
        $product_categories = ProductCategory::where('bistro_id', $bistro->id)->paginate(10);
        $data['data'] = [
            'product_categories' => $this->factalPaginator($product_categories, ProductCategoryTransformer::forBackendStatis())
        ];
        return $this->apiSuccess($data);
    }

    /**
     * 商品分类
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request) {
        $bistro = $request->user('bistro');
        $name = $request->input('name');
        $product_categories = ProductCategory::where('bistro_id', $bistro->id)->name($name)->orderby('id', 'desc')->paginate(10);
        $data['data'] = [
            'product_categories' => $this->factalPaginator($product_categories, new ProductCategoryTransformer())
        ];
        return $this->apiSuccess($data);
    }

    public function categoryAll() {
        $product_categories = ProductCategory::get();
        $data = [
          'categories' => $this->fractalItems($product_categories, new ProductCategoryTransformer())
        ];
        return $this->apiSuccess($data);
    }

    /**
     * 商品分类详情
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail($id) {//目前没加分页
        $product_category = ProductCategory::findorfail($id);
        $products = $product_category->product()->get()->toArray();
        $product_ids = '';
        foreach ($products as $p) {
           $product_ids .= $p['id'].',';
        }
        $product_ids = substr($product_ids,0, -1);
        if(!empty($product_ids)) {
            $sql = "select sum(sale_count) as sum_sale_count, sum(total_amount) as sum_total_amount,date from product_sale_days where product_id in ({$product_ids}) group by date ";
            $result = DB::select($sql);

            $sql_month = "select sum(sale_count) as sum_sale_count, sum(total_amount) as sum_total_amount,month from product_sale_months where product_id in ({$product_ids}) group by month ";
            $result_month = DB::select($sql_month);
            $data['data'] = [
                'product_category' => $this->fractalItem($product_category, new ProductCategoryTransformer()),
                'day' => $result,
                'month' => $result_month
            ];
        }else{
            $data['data'] = [
                'product_category' => $this->fractalItem($product_category, new ProductCategoryTransformer()),
                'day' => [],
                'month' => []
            ];
        }
        return $this->apiSuccess($data);
    }

    /**
     * 删除商品分类
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete($id) {
        $product_category = ProductCategory::findorfail($id);
        $product_category->delete();
        return $this->apiSuccess();
    }

    /**
     * 修改商品分类
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request, $id) {
        $bistro = $request->user('bistro');
        $input = $request->all();
        $validateResult = $this->validateCreateProductCategory($input);
        if ($validateResult["errorCode"] > 0) return $this->apiError($validateResult["message"], $validateResult["errorCode"]);
        $product_category = ProductCategory::findorfail($id);
        $product_category->name = $input['name'];
        $product_category->save();
        $data['data'] = [
            'product_category' => $this->fractalItem($product_category, new ProductCategoryTransformer())
        ];
        return $this->apiSuccess($data);
    }

    /**
     * 创建商品分类
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function create(Request $request) {
        $bistro = $request->user('bistro');
        $input = $request->all();
        $validateResult = $this->validateCreateProductCategory($input);
        if ($validateResult["errorCode"] > 0) return $this->apiError($validateResult["message"], $validateResult["errorCode"]);


        $product_category = $this->_setProductCategory(new ProductCategory(), $input, $bistro);
        $product_category->save();

        $data['data'] = [
            'product_category' => $this->fractalItem($product_category, new ProductCategoryTransformer())
        ];

        return $this->apiSuccess($data);
    }

    private function _setProductCategory($product_category, $input, $bistro) {
        $product_category->bistro_id = $bistro->id;
        $product_category->name = $input['name'];
        return $product_category;
    }

    private function validateCreateProductCategory($input) {
        $name = isset($input['name']) ? $input['name']: '';
        if(empty($name)){
            return [
                "message" => "点名不得为空",
                "errorCode" => 5000
            ];
        }

        return [
            "message" => "没有错误信息",
            "errorCode" => 0
        ];

    }
}
